/**
 * @see 该界面是“学生界面”
 * @see 主要功能有：学生查看自己的考勤情况、签到
 */
import { formatCurrentDay, failLocationAttend } from '../../../../utils/util'
import { GAODE_CONFIG } from '../../../../config'
import amapFile from '../../../../plugins/amap-wx'
import behaviors from './behavior'

// 高德地图：微信小程序
const gaodeKey = GAODE_CONFIG.key //申请的高德地图key
const myAmapFun = new amapFile.AMapWX({ key: gaodeKey })

Component({
  behaviors: [behaviors],
  options: {
    addGlobalClass: true // 组件显示不了icon，加上addGlobalClass
  },
  data: {
    courseData: [], // 课程数据data
    currWeek: '', // 当前第几周
    currDayTime: '', // 当前星期几
    viewCourseData: [], // 渲染课程数据data
    stuAttendData: [], // 学生考勤列表（第3个tabs)

    bIsAttendInfoShow: false, // "定位签到"弹窗是否显示
    bIsSuccessShow: false, // "定位签到成功"弹窗是否显示
    bIsInvitationCodeShow: false, // "邀请码签到"是否显示
    bIsLocationShow: false, // "您现在所处位置弹窗"是否显示

    currentItem: 0, // 考勤限时点击当前项
    attendanceValue: {}, // '签到'点击子组件传过来的参数
    attendanceWay: '', // '开启考勤'的方式
    form: {
      timeValue: '5', // 考勤限时的值
      distanceInit: '200', // 距离范围input初始值
      lateInit: '0', // 迟到时间input初始值
      latitude: '', // 纬度
      longitude: '', // 经度
      attendanceLocation: '' // 地图定位位置
    }
  },
  lifetimes: {
    ready () {
      // 获取学生课程
      this.getStuCourseInfo()
    }
  },
  methods: {
    refreshData () {
      this.setData({ refreshing: true })
      this.clickMsgButton()
    },
    /**
     * @see 获取定位
     */
    locationAttend () {
      wx.showLoading({
        title: '正在定位中...',
        icon: 'loading'
      })
      wx.getLocation({
        type: 'gcj02',
        isHighAccuracy: true,
        success: (res) => {
          const { latitude, longitude } = res
          this.loadCity(latitude, longitude)
        },
        fail: (res) => {
          console.log(res)
          wx.hideLoading()
          failLocationAttend(res)
        }
      })
    },
    /**
     * @see 高德地图获取位置（把当前位置的经纬度传给高德地图，调用高德API获取当前地理位置）
     */
    loadCity (latitude, longitude) {
      myAmapFun.getRegeo({
        location: longitude + ',' + latitude, // location的格式为'经度,纬度'
        success: (data) => {
          wx.hideLoading()
          this.setData({
            'form.latitude': latitude,
            'form.longitude': longitude,
            'form.attendanceLocation': `${data[0].regeocodeData.formatted_address}附近`
          })
        },
        fail: (info) => {
          this.loadCity(latitude, longitude)
        }
      })
    },
    /**
     * @see 点击结束考勤
     */
    endAttendanceConfirm () {
      wx.showModal({
        title: '提示',
        content: '是否结束考勤？',
        success: (res) => {
          if (res.confirm) {
            this.endAttendance()
          } else if (res.cancel) {
            wx.showToast({
              title: '取消结束考勤',
              icon: 'none'
            })
          }
        }
      })
    },
    /**
     * @see 点击选择周数（第几周）
     */
    bindWeekChange (e) {
      this.setData({
        weekIndex: e.detail.value
      })
      this.clickMsgButton()
    },
    /**
    * @see 点击Tabs菜单
    */
    tabClick (e) {
      let { offsetLeft, id } = e.currentTarget
      id = parseInt(id)
      this.setData({
        sliderOffset: offsetLeft,
        activeIndex: id,
        'appMsg.show': false
      })
      this.handleTabData(id)
    },
    handleTabData (tabActiveIndex, isHasRequestStuAttCount = false) {
      const { courseData, currDayTime } = this.data
      switch (tabActiveIndex) {
        case 0:
          const viewCourseData = courseData.filter((item) => {
            return item.dayTime == currDayTime
          })
          if (!viewCourseData.length) {
            this.setData({
              appMsg: {
                type: 'none',
                show: true
              }
            })
          }
          this.setData({ viewCourseData })
          break
        case 1:
          if (!courseData.length) {
            this.setData({
              appMsg: {
                type: 'none',
                show: true
              }
            })
          }
          this.setData({ viewCourseData: courseData })
          break
        case 2:
          if (!this.data.stuAttendData.length && !isHasRequestStuAttCount) {
            // 请求接口拿到数据
            this.getStudentAttendanceCount()
          }
          break
        default:
      }
    },
    /**
    * @see 点击“签到”按钮(子组件传过来的数据)
    */
    stuAttend (e) {
      const attendanceValue = e.detail.item
      const { showButton, attendanceWay } = attendanceValue
      const locationAttend = () => {
        this.setData({ bIsLocationShow: true, attendanceWay: 1 })
        this.locationAttend()
      }
      const scanCodeAttend = () => {
        wx.scanCode({
          onlyFromCamera: true,
          success: (res) => {
            let { result } = res
            try {
              result = JSON.parse(result)
              this.setData({ attendanceWay: 2 })
              this.signIn(result)
            } catch (error) {
              wx.showModal({
                title: '提示',
                content: '二维码参数异常!',
                showCancel: false
              })
            }
          }
        })
      }
      this.setData({ attendanceValue })
      if (showButton === 1) { // 显示签到按钮
        switch (attendanceWay) { // 签到方式
          case 1: // 定位签到
            locationAttend()
            break
          case 2: // 扫一扫签到
            scanCodeAttend()
            break
          case 3: // 邀请码签到
            break
          default:
            break
        }
      } else if (showButton === 3) { // 定位签到位置异常
        locationAttend()
      }
    },
    /**
     * @see 定位签到点击“您现在所处位置-确定”按钮
     */
    bindLocationConfirm () {
      this.signIn()
    },
    /**
     * @see 定位签到点击“您现在所处位置-重新获取位置”按钮
     */
    bindGetLocation () {
      this.locationAttend()
    },
    /**
    * @see 邀请码签到点击“确定”按钮
    */
    bindConfirm () {
      const { stuIdValue } = this.data
      if (stuIdValue == '') {
        wx.showToast({
          title: '请输入学号',
          icon: 'none'
        })
        return
      } else {
        this.setData({
          bIsInvitationCodeShow: false
        })
      }
    },
    /**
     * @see 邀请码签到点击“取消”按钮
     */
    bindCancel () {
      this.setData({
        bIsInvitationCodeShow: false
      })
    },
    /**
    * @see 点击授权课程
    */
    clickAuthorizeClass (e) {
      const { bIsLight } = e.currentTarget.dataset.color
      const { currDayTime } = this.data
      if (bIsLight) {
        this.setData({
          bIsAuthorize: false,
          authorize: {
            bgColor: '',
            color: '#ffffff',
            bIsLight: false
          },
          tabs: [formatCurrentDay(currDayTime), '周期课程', '考勤记录'],
          tabsWidth: '33.33%',
          activeIndex: 0,
          sliderOffset: 0,
          sliderLeft: 0
        })
        this.getStuCourseInfo()
      } else {
        this.setData({
          bIsAuthorize: true,
          authorize: {
            bgColor: '#ffffff',
            color: '#2172ED',
            bIsLight: true
          },
          tabs: [formatCurrentDay(currDayTime), '周期课程'],
          tabsWidth: '50%',
          activeIndex: 0,
          sliderOffset: 0,
          sliderLeft: 0
        })
        this.getAuthorizationCourse()
      }
    },
    /**
    * @see 点击“开启考勤”按钮
    */
    openAttendance (e) {
      const attendanceValue = e.detail.item
      const { showButton } = attendanceValue
      this.setData({ attendanceValue })
      switch (showButton) {
        case 5: // 开始考勤
          this.selectAttendanceWay()
          return
        case 6: // 结束考勤
          this.endAttendanceConfirm()
          return
      }
    },
    selectAttendanceWay () {
      wx.showActionSheet({
        // itemList: ['定位签到', '邀请码签到'],
        itemList: ['定位签到'],
        success: (res) => {
          if (res.tapIndex == 0) {
            this.setData({
              attendanceWay: 1,
              bIsAttendInfoShow: true
            })
            this.locationAttend()
          } else if (res.tapIndex == 1) {
            this.setData({
              attendanceWay: 3,
              bIsInvitationCodeShow: true
            })
            // this.codeAttend()
          }
        },
        fail (res) {
          wx.showToast({
            title: '出错啦~请再试一次~',
            icon: 'none'
          })
        }
      })
    },
    /**
      * @see 点击定位签到“确定”按钮
      */
    bindAttendInfoConfirm () {
      const { form } = this.data
      if (!form.timeValue) {
        wx.showToast({
          title: '请填写考勤限时~',
          icon: 'none'
        })
        return
      }
      this.startAttendance()
    },
    /**
     * @see 点击开启考勤“×”按钮
     */
    bindAttendInfoCancel () {
      this.setData({
        bIsAttendInfoShow: false
      })
    },
    /**
     * @see 点击“考勤限时”
     */
    bindEveryTime (e) {
      const { index, item } = e.currentTarget.dataset
      this.setData({
        currentItem: index,
        'form.timeValue': item.value
      })
    },
    /**
     * @see “考勤限时-时间设置”input点击时触发
     */
    bindInputBox (e) {
      this.setData({
        currentItem: null
      })
    },
    /**
     * @see 修改input绑定值
     */
    bindKeyInput (e) {
      const { currentTarget, detail } = e
      this.setData({
        ['form.' + currentTarget.dataset.name]: detail.value
      })
    },
    /**
     * @see 点击刷新页面
     */
    clickMsgButton () {
      const { bIsAuthorize, activeIndex } = this.data
      if (bIsAuthorize) {
        this.getAuthorizationCourse()
      } else {
        if (activeIndex === 0 || activeIndex === 1) {
          this.getStuCourseInfo()
        } else {
          // 获取考勤记录
          this.getStudentAttendanceCount()
        }
      }
    }
  }
})